package com.carpool.finder;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.slidingmenu.lib.SlidingMenuActivity;

public class RouteActivity extends SlidingMenuActivity{
	
	ImageView profile;
	TextView tvname;
	TextView tvloc;
	TextView tvloc2;
	TextView tvloc3;
	HashMap<String,String> user;
	DatabaseHandler db;
	Button btnMap;
	Button btnMap2;
	Button btnMap3;
	Intent mapIntent;
	
	//JSON Response code names
	
	 private static String KEY_SUCCESS = "success";
	 private static String KEY_ERROR = "error";
	 private static String KEY_ERROR_MSG = "error_msg";
	 private static String KEY_NID = "uid";
	 private static String KEY_SNAME = "src_name";
	 private static String KEY_DNAME = "des_name";
	 private static String KEY_VNAME = "via_name";
	 
	 Button btnRegister;
	 String uid;
	 

		//Menu Buttons
		Button home;
		Button search;
		Button route;
		Button logout;
	 
	ImageFinder im = new ImageFinder();
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.route);
        setBehindContentView(R.layout.menu);
        setBehindOffset((int)getResources().getDimension(R.dimen.actionbar_home_width));
		setBehindScrollScale(0.5f);
		
		logout = (Button)findViewById(R.id.logout_but);
		home = (Button)findViewById(R.id.btn_home);
		search = (Button)findViewById(R.id.btn_search);
		route = (Button)findViewById(R.id.btn_route);
		
		btnRegister = (Button) findViewById(R.id.btnRegister);
		db=new DatabaseHandler(getApplicationContext());
		profile = (ImageView)findViewById(R.id.profile_pic);
		tvname = (TextView)findViewById(R.id.name);
		tvloc = (TextView)findViewById(R.id.locationstart);
		tvloc2 = (TextView)findViewById(R.id.locationend);
		tvloc3 = (TextView)findViewById(R.id.locationvia);
		if (android.os.Build.VERSION.SDK_INT > 9) {
		      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		      StrictMode.setThreadPolicy(policy);
		}
		btnMap = (Button) findViewById(R.id.map_btn);
		btnMap2 = (Button) findViewById(R.id.map_btn2);
		btnMap3 = (Button) findViewById(R.id.map_btn3);
		user = new HashMap<String,String>();
		user=db.getUserDetails();
		String name = user.get("name");
		String email = user.get("email");
		uid = user.get("uid");
		Log.e("UID :", uid);
		//String phone = user.get("phone");
		String image_url = user.get("image");
		tvname.setText(""+name);
		Bitmap bitmap = im.findImage(image_url);
		profile.setImageBitmap(bitmap);
		mapIntent = new Intent(getApplicationContext(), GoogleMapActivity.class);
		
		/*
		 * Route registration
		 */
		
		btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String start = tvloc.getText().toString();
                String end = tvloc2.getText().toString();
                String via = tvloc3.getText().toString();
                
                //splitting strings
                String src[] = start.split(",");
                String des[] = end.split(",");
                String mid[] = via.split(",");
                
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerRoute(uid,src[0],src[1],src[2],des[0],des[1],des[2],mid[0],mid[1],mid[2]);
 
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        //registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // Route successfully registred
                            // Store user details in SQLite Database
                            JSONObject json_user = json.getJSONObject("route");
 
                            // Clear all previous data in database
                            //userFunction.logoutUser(getApplicationContext());
                            Toast.makeText(getBaseContext(), "Route Registered!!", Toast.LENGTH_SHORT).show();
                            //db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), HomeActivity.class);
                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                            // Close Registration Screen
                            finish();
                        }else{
                            // Error in registration
                            //registerErrorMsg.setText("Error occured in registration");
                        	Toast.makeText(getBaseContext(), "Error!!", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
		
		/*
		 * Button click listeners
		 */
		btnMap.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				mapIntent.putExtra("command", "start");
				startActivityForResult(mapIntent, 1);
			}
		});
		
		btnMap2.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Intent mapIntent = new Intent(getApplicationContext(), GoogleMapActivity.class);
				mapIntent.putExtra("command", "end");
				startActivityForResult(mapIntent, 1);
			}
		});
		
		btnMap3.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Intent mapIntent = new Intent(getApplicationContext(), GoogleMapActivity.class);
				mapIntent.putExtra("command", "via");
				startActivityForResult(mapIntent, 1);
			}
		});
		
		logout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), LoginActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
			}
		});
		
		route.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), ViewRouteActivity.class);
				startActivity(i);
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
				
			}
		});
		
		search.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		
		home.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), HomeActivity.class);
				startActivity(i);
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
				finish();
				
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	  super.onActivityResult(requestCode, resultCode, data);
	  if(data.getExtras().containsKey("locationstart")){
		  tvloc.setText(data.getStringExtra("locationstart"));
	  }
	  if(data.getExtras().containsKey("locationend")){
		  tvloc2.setText(data.getStringExtra("locationend"));
	  } 
	  if(data.getExtras().containsKey("locationvia")){
		  tvloc3.setText(data.getStringExtra("locationvia"));
	  } 
	} 

}